/**
 * 文档工具
 */
function sDocUtil(){
    /**
     * 导出文件
     * @param data 需要保存的内容
     * @param name 保存的文件名 
     */
    this.exportfiles = function(data, name) {
        //Blob为js的一个对象，表示一个不可变的, 原始数据的类似文件对象，这是创建文件中不可缺少的！
        var urlObject = window.URL || window.webkitURL || window;
        var export_blob = new Blob([data]);
        var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
        save_link.href = urlObject.createObjectURL(export_blob);
        save_link.download = name;
        save_link.click();
    }

    /**
     * 格式化时间
     * @param {}} date 
     * @returns 格式化的时间字符串
     */
    this.formatDate = function (date, format) {
        var o = {
            "M+": date.getMonth() + 1, 
            "d+": date.getDate(),    
            "h+": date.getHours(),   
            "m+": date.getMinutes(), 
            "s+": date.getSeconds(), 
            "q+": Math.floor((date.getMonth() + 3) / 3),   
            "S": date.getMilliseconds() 
        }
        if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
                RegExp.$1.length == 1 ? o[k] :
                    ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    }

    /**
     * 打开文件
     * @param {*} type 文件类型
     * @param {*} callback 回调方法
     */
    this.openFile = function(type, callback){
        var input=document.createElement('input')
        input.setAttribute('id','_ef');
        input.setAttribute('type','file');
        input.setAttribute("style",'visibility:hidden');
        input.setAttribute('accept', type);
        document.body.appendChild(input);
        input.addEventListener("change", (e)=>{
          if(callback){
            callback(e);
          }
        })
        input.click();
    }

    /**
     * base64转图片
     * @param {*} base64 
     */
    this.convertBase64ToImg = function(base64, callback){
        if(!base64) return;
        const img = new Image();
		img.src = base64;
		img.onload = function () {
            callback(img);
		}
    }

    /**
     * 将图片文件转成base64 
     * @param {*} file 
     * @param {*} callback 
     */
    this.convertImgFileToBase64 = function(file, callback) {
        const fileReader = new FileReader();
        fileReader.readAsDataURL(file);
        fileReader.onload = () => {
            callback(fileReader.result)
        }
    }

    /**
     * 将字符串转成base64编码
     * @param {*} str 字符串
     * @returns 
     */
    this.convertStringToBase64 = function(str){
        return btoa(str);
    }

    /**
     * 判断是否是数字
     * @param {*} val 
     */
    this.isNumber = function(val){
        return /^[0-9]+([.]{1}[0-9]+){0,1}$/.test(val);
    }

    /**
     * 按指定换算率转换大小
     * @param {*} obj 包含数字属性的对象
     * @param {*} ratio 换算率
     * @param {*} zoom 缩放率
     */
    this.convertByMutiRatioZoom = function(obj, ratio, zoom){
        for(var i in obj){
            if(typeof(obj[i]) == "object"){
                this.convertByMutiRatioZoom(obj[i], ratio, zoom);
            }else if(typeof(obj[i]) == "number"){
                obj[i] = obj[i] * ratio * zoom;
            }
        }
    }

    /**
     * 按指定换算率转换size大小
     * @param {*} obj 包含数字属性的对象
     * @param {*} ratio 换算率
     * @param {*} zoom 缩放率
     * @param {*} props
     */
    this.convertByMutiRatioDivideZoom = function(obj, ratio, zoom, props){
        for(var i in obj){
            if(typeof(obj[i]) == "object"){
                this.convertByMutiRatioDivideZoom(obj[i], ratio, zoom);
            }else if(!props || props.indexOf(i) > -1){
                obj[i] = obj[i] * ratio / zoom;
            }
        }
    }

    /**
     * 按指定换算率转换size大小
     * @param {*} obj 包含数字属性的对象 
     * @param {*} ratio 
     * @param {*} props 
     */
    this.convertByDivideRatio = function(obj, ratio, props){
        for(var i in obj){
            if(typeof(obj[i]) == "object"){
                this.convertByDivideRatio(obj[i], ratio, zoom);
            }else if(!props || props.indexOf(i) > -1){
                obj[i] = obj[i] / ratio;
            }
        }
    }

    /**
     * 对导入的JSON进行解压
     */
    this.decompressJson = function(json){
        var s = null;
        var index = -1;

        var merge = function (jsonObj, jo) {
            let hasStyle = false;

            for (let i in jsonObj) {
                if(!jsonObj[i]) continue;
                
                if (i == "style") {
                    hasStyle = true;
                    s = jsonObj[i];
                    
                    if(s && s.indexOf && s.indexOf("_") > -1) {
                        index = parseFloat(s.split("_")[1]);
                    
                        if(typeof(jo.styles[index]) == "object"){
                            jsonObj[i] = {...jo.styles[index]};
                        }else{
                            jsonObj[i] = JSON.parse(jo.styles[index]);
                        }
                    }

                    setTempProp(jsonObj);
                }else if(i == "children"){
                    merge(jsonObj[i], jo);
                }else if(
                    jsonObj[i]._sType || 
                    i == "children" || 
                    i == "rows" || 
                    i == "cells"){

                    merge(jsonObj[i], jo);
                }
            }

            if(!hasStyle && jsonObj._sType){
                setTempProp(jsonObj);
            }
        }

        merge(json, json);
        json.styles = null;

        return json;
    }

    var tempProps = [
        "display", 
        "lineWidth", 
        "lineDash", 
        "width", 
        "height"
    ];

    /**
     * 设置样式临时属性
     * @param {*} jsonObj 
     */
    var setTempProp = function(jsonObj){
        let name = null;

        for(let i in tempProps){
            name = "$" + tempProps[i];
            if(!jsonObj[name]) continue;

            jsonObj.style = jsonObj.style ? jsonObj.style : {};
            jsonObj.style[tempProps[i]] = jsonObj[name];
            delete jsonObj[name];
        }
    }

    /**
     * 对导出的JSON进行压缩
     * @param {*} json 
     */
    this.compressJson = function (json) {
        var styles = [];
        var s = null;
        var index = -1;

        var group = function (jsonObj) {
            for (let i in jsonObj) {
                if(!jsonObj[i] || i.indexOf("__") > -1) continue;

                if (i == "style") {
                    s = JSON.stringify(jsonObj[i]);
                    index = styles.indexOf(s);

                    if (index < 0) {
                        styles.push(s);
                        index = styles.length - 1;
                    }

                    jsonObj[i] = "style_" + index;
                }else if(
                    jsonObj[i]._sType || 
                    i == "children" || 
                    i == "rows" || 
                    i == "cells"){

                    group(jsonObj[i]);
                }
            }
        }

        group(json);
        json.styles = styles;

        return json;
    };

    /**
     * 将blob转成字符串
     * @param {*} blob 
     * @returns 
     */
    this.blobToString = function(blob) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsText(blob);
            reader.onload = () => {
                resolve(reader.result);
            };
            reader.onerror = reject;
        });
    }

    /**
     * 将图片blob转base64
     * @param {*} blob 
     * @returns 
     */
    this.imgBlobToBase64 = function(blob){
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onload = () => {
                resolve(reader.result);
            };
            reader.onerror = reject;
        });
    }

    /**
     * json转xml
     * @param {*} json 
     * @returns 
     */
    this.jsonToXml = function(json) {
        var xml = "<?xml version=\"1.0\" encoding='UTF-8'?>";
        var recursive = function(json, xml){
            if(json._sType){
                xml += "<" + json._sType + ">";
            }

            for (let key in json) {
                let value = json[key];
                
                if(value instanceof Function || key == "_sType") continue;

                xml += "<" + key + ">";

                if(Array.isArray(value)) {
                    if(key == "styles"){
                        for(let i in value){
                            xml += "<style_" + i + ">";
                            xml = recursive(JSON.parse(value[i]), xml);
                            xml += "</style_" + i + ">";
                        }
                    }else{
                        for (let i = 0; i < value.length; i++) {
                            xml = recursive(value[i], xml);
                        }
                    }
                }else if(value instanceof Object) {
                    xml = recursive(value, xml);
                }else {
                    xml += value;
                }

                xml += "</" + key + ">";
            }

            if(json._sType){
                xml += "</" + json._sType + ">";
            }

            return xml;
        }
        
        xml = recursive(json, xml);
        return xml;
    }
}